package hello.word.m2.maven.locator;

import org.jdbi.v3.core.config.ConfigRegistry;
import org.jdbi.v3.core.locator.ClasspathSqlLocator;
import org.jdbi.v3.core.locator.internal.ClasspathBuilder;
import org.jdbi.v3.sqlobject.SqlObjects;
import org.jdbi.v3.sqlobject.config.Configurer;
import org.jdbi.v3.sqlobject.internal.SqlAnnotations;
import org.jdbi.v3.sqlobject.locator.SqlLocator;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.function.Function;

public class JdbiSqlObjectClasspathLocatorImpl implements SqlLocator, Configurer {

	@Override
	public String locate(Class<?> sqlObjectType, Method method, ConfigRegistry config) {
		Function<String, String> valueOrMethodNameToSql = key -> {
			String filename = key.isEmpty() ? method.getName() : key;
			String path = new ClasspathBuilder().appendDotPath(sqlObjectType.getName()).build() + "." + filename
					+ ".sql";
			return ClasspathSqlLocator.getResourceOnClasspath(sqlObjectType.getClassLoader(), path);
		};
		return SqlAnnotations.getAnnotationValue(method, valueOrMethodNameToSql).orElseThrow(
				() -> new IllegalStateException(String.format("method %s has no query annotations", method)));
	}

	@Override
	public void configureForType(ConfigRegistry registry, Annotation annotation, Class<?> sqlObjectType) {
		registry.get(SqlObjects.class).setSqlLocator(this);
	}

	@Override
	public void configureForMethod(ConfigRegistry registry, Annotation annotation, Class<?> sqlObjectType,
			Method method) {
		configureForType(registry, annotation, sqlObjectType);
	}
}
